﻿using System.Web;

namespace Nana.Web.Compressing
{
  public static class CompressHelpers
  {
    public static ResponseFilterFactory PickCompressFilterFactory(this HttpContext context)
    {
      // this means there must be something wrong, maybe already using cache
      if (null == context.Handler) return null;

      // don't compress if Vary doesn't contain Accept-Encoding
      if (!context.Response.Cache.VaryByHeaders[hhAcceptEncoding])
        return null;

      if (!context.Response.ContentType.IsCompresseTargetType())
        return null;

      // 静态和非静态内容可能采用不同的策略
      return context.IsStaticHandler() ?
        context.GetStaticCompressFactory() :
        context.GetDynamicCompressFactory();
    }

    private const string hhAcceptEncoding = "Accept-Encoding";

    public static bool IsCompresseTargetType(this string contentType)
    {
      if (CompressionModule.alwaysDoTextSub && contentType.ToUpperInvariant().StartsWith("TEXT/"))
        return true;

      foreach (var tester in CompressionModule.typeTesterList)
      {
        if (tester.Pattern.IsMatch(contentType))
          return tester.ShouldCompress;
      }

      return false;
    }

    #region static compress
    public static ResponseFilterFactory GetStaticCompressFactory(this string acceptEncoding)
    {
      foreach (var item in CompressionModule.staticFilterList)
      {
        if (item.Pattern.IsMatch(acceptEncoding))
          return item.Factory;
      }

      return null;
    }
    public static ResponseFilterFactory GetStaticCompressFactory(this HttpRequest request)
    {
      return request.Headers[hhAcceptEncoding].GetStaticCompressFactory();
    }
    public static ResponseFilterFactory GetStaticCompressFactory(this HttpContext context)
    {
      return context.Request.GetStaticCompressFactory();
    }
    #endregion

    #region dynamic compress
    public static ResponseFilterFactory GetDynamicCompressFactory(this string acceptEncoding)
    {
      foreach (var item in CompressionModule.dynamicFilterList)
      {
        if (item.Pattern.IsMatch(acceptEncoding))
          return item.Factory;
      }

      return null;
    }
    public static ResponseFilterFactory GetDynamicCompressFactory(this HttpRequest request)
    {
      return request.Headers[hhAcceptEncoding].GetDynamicCompressFactory();
    }
    public static ResponseFilterFactory GetDynamicCompressFactory(this HttpContext context)
    {
      return context.Request.GetDynamicCompressFactory();
    }
    #endregion
  }
}
